package com.cd.song.controller;

import com.cd.common.controller.BaseController;
import com.cd.common.domain.AjaxResult;
import com.cd.song.api.SongTagService;
import com.cd.song.jpa.domain.SongTag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/song-tags")
public class SongTagController extends BaseController {

    @Autowired
    private SongTagService songTagService;

    @GetMapping
    public AjaxResult getAllSongTags() {
        return success(songTagService.findAll());
    }

    @GetMapping("/{id}")
    public AjaxResult getSongTagById(@PathVariable(value = "id") Long songTagId) {
        Optional<SongTag> songTag = songTagService.findById(songTagId);
        if (songTag.isPresent()) {
            return success();
        } else {
            return error();
        }
    }

    @PostMapping
    public AjaxResult createSongTag(@RequestBody SongTag songTag) {
        return success(songTagService.save(songTag));
    }

    @PutMapping("/{id}")
    public AjaxResult updateSongTag(@PathVariable(value = "id") Long songTagId, @RequestBody SongTag songTagDetails) {
        Optional<SongTag> optionalSongTag = songTagService.findById(songTagId);
        if (optionalSongTag.isPresent()) {
            SongTag songTag = optionalSongTag.get();
            songTag.setName(songTagDetails.getName());
            songTag.setUserId(songTagDetails.getUserId());
            songTag.setIsDeleted(songTagDetails.getIsDeleted());
            final SongTag updatedSongTag = songTagService.save(songTag);
            return success();
        } else {
            return error();
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteSongTag(@PathVariable(value = "id") Long songTagId) {
        Optional<SongTag> songTag = songTagService.findById(songTagId);
        if (songTag.isPresent()) {
            songTagService.deleteById(songTagId);
            return success();
        } else {
            return error();
        }
    }
}